package com.ydlclass.registry.util;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author it楠老师
 * @createTime 2023-03-23
 */
public class ServiceHolder {

    private final static ServiceHolder serviceHolder = new ServiceHolder();

    private final Map<String, List<InetSocketAddress>> service = new ConcurrentHashMap<>(16);

    private ServiceHolder() {
    }

    public static ServiceHolder getInstance() {
        return serviceHolder;
    }

    public void add(String serviceName, List<InetSocketAddress> inetSocketAddresses) {
        if (serviceName == null || "".equals(serviceName)
                || inetSocketAddresses == null || inetSocketAddresses.size() == 0) {
            throw new IllegalArgumentException("您必须传入一个有效的服务名和服务列表！");
        }
        service.put(serviceName, inetSocketAddresses);
    }

    public void addNewService(String serviceName, InetSocketAddress inetSocketAddress) {
        List<InetSocketAddress> inetSocketAddresses = service.get(serviceName);
        if (inetSocketAddresses == null) {
            inetSocketAddresses = new ArrayList<>();
        }
        inetSocketAddresses.add(inetSocketAddress);
        service.put(serviceName, inetSocketAddresses);
    }

    public void offlineService(String serviceName, InetSocketAddress inetSocketAddress){
        List<InetSocketAddress> inetSocketAddresses = service.get(serviceName);
        if(inetSocketAddresses == null || inetSocketAddresses.size() == 0){
            return;
        }
        inetSocketAddresses.remove(inetSocketAddress);
    }

    public void offlineService(String serviceName){
        service.remove(serviceName);
    }


    public List<InetSocketAddress> getRemoteAddress(String serviceName){
        return service.get(serviceName);
    }
}
